<script>
import Qrcode from 'qrcodejs2'
import copy from 'copy-to-clipboard';
import {getUrl} from "@/util/aihuman/getUrl";
import {getDetail, updateProjectConfig} from "@/api/aihuman/IntelligentInteraction/IntelligentInteraction";

export default {
  name: "ReleaseDialogTemp",
  data() {
    return {
      dialogVisible: false,
      itemsData: {},
      qrcode: null,
      showQr: false,

      form: {
        "createRoomParam": {
          "ASRConfig": {
            "APPID": "",
            "APP_KEY": "",
            "KEY_SECRET": "",
            "LANGUAGE": "",
            "MAX_SECONDS_PER_SENTENCE": 0,
            "NL_VALIDATE": false,
            "SAMPLE_RATE": 0,
            "TOKEN": "",
            "USER": "",
            "VAD_SILENCE_MS": 0,
            "WS_URI": ""
          },
          "ASRType": "",
          "TTSConfig": {
            "API_KEY": "",
            "API_REGION": "",
            "API_URL": "",
            "SPEED": 0,
            "STREAM_URL": "",
            "VOICE": ""
          },
          "TTSType": "",
          "assistantType": "",
          "initialState": "",
          "knowledgeRobotConfig": {
            "ACTIONS_URL": "",
            "CHANNEL_TYPE": 0,
            "CONVERSATION_RECORD_URL": "",
            "CONVERSATION_URL": "",
            "DIGITAL_RES_URL": "",
            "DISCONTINUE_REGEX_PATTERNS": [],
            "DISCONTINUE_WORDS": [],
            "FLOW_FIRST": false,
            "SLEEP_DIGITAL_RESOURCE": "",
            "SLEEP_REGEX_PATTERNS": [],
            "SLEEP_RESPONSE": "",
            "SLEEP_WORDS": [],
            "TENANT_ID": "",
            "UNK_RESPONSE": "",
            "WAKEUP_DIGITAL_RESOURCE": "",
            "WAKEUP_FLOW_NODE_NAME": "",
            "WAKEUP_FLOW_TEMPLATE_ID": "",
            "WAKEUP_REGEX_PATTERNS": [],
            "WAKEUP_RESPONSE": "",
            "WAKEUP_WORDS": []
          },
          "knowledgeRobotInstanceId": "",
          "llmConfig": {
            "FREQUENCY_PENALTY": 0,
            "LLM_URL": "",
            "MAX_TOKENS": 0,
            "MODEL_NAME": "",
            "NSFW_RESPONSE": "",
            "PRESENCE_PENALTY": 0,
            "PROMPT_TEMPLATE_WITHOUT_SEARCH": "",
            "RAG_TEMPLATE": "",
            "RAG_URL": "",
            "SYSTEM_PROMPT": "",
            "TEMPERATURE": 0,
            "TOP_P": 0,
            "USE_RAG": false
          },
          "llmToken": "",
          "roomType": ""
        },
        "livektUrlInfo": {
          "allRoomsUrl": "",
          "closeRoomUrl": "",
          "getRoomTokenUrl": "",
          "roomInfoUrl": "",
          "wsUrl": ""
        }
      },
      rules: {},
      loading: false // 添加 loading 属性
    }
  },
  methods: {
    isObject(obj) {
      return obj.constructor === Object;
    },
    async submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.loading = true; // 设置 loading 为 true
          try {
            const {data} = await updateProjectConfig({
              id: this.itemsData.id,
              projectConfig: JSON.stringify(this.form)
            });
            this.$message.success(data.msg);
            this.dialogVisible = false;
          } catch (error) {
            console.error('更新项目配置失败:', error);
            this.$message.error('更新项目配置失败，请稍后再试');
          } finally {
            this.loading = false; // 设置 loading 为 false
          }
        } else {
          console.log('校验失败!');
          return false;
        }
      });
    },
    async open(data) {
      this.dialogVisible = true
      this.itemsData = data

      this.$nextTick(() => {
        this.creatQrCode();
      })


      try {
        const res = await getDetail({
          id: this.itemsData.id
        });
        if (res.data.data.projectConfig === null) {
          this.form = {
            "createRoomParam": {
              "ASRConfig": {
                "APPID": "",
                "APP_KEY": "",
                "KEY_SECRET": "",
                "LANGUAGE": "",
                "MAX_SECONDS_PER_SENTENCE": 0,
                "NL_VALIDATE": false,
                "SAMPLE_RATE": 0,
                "TOKEN": "",
                "USER": "",
                "VAD_SILENCE_MS": 0,
                "WS_URI": ""
              },
              "ASRType": "",
              "TTSConfig": {
                "API_KEY": "",
                "API_REGION": "",
                "API_URL": "",
                "SPEED": 0,
                "STREAM_URL": "",
                "VOICE": ""
              },
              "TTSType": "",
              "assistantType": "",
              "initialState": "",
              "knowledgeRobotConfig": {
                "ACTIONS_URL": "",
                "CHANNEL_TYPE": 0,
                "CONVERSATION_RECORD_URL": "",
                "CONVERSATION_URL": "",
                "DIGITAL_RES_URL": "",
                "DISCONTINUE_REGEX_PATTERNS": [],
                "DISCONTINUE_WORDS": [],
                "FLOW_FIRST": false,
                "SLEEP_DIGITAL_RESOURCE": "",
                "SLEEP_REGEX_PATTERNS": [],
                "SLEEP_RESPONSE": "",
                "SLEEP_WORDS": [],
                "TENANT_ID": "",
                "UNK_RESPONSE": "",
                "WAKEUP_DIGITAL_RESOURCE": "",
                "WAKEUP_FLOW_NODE_NAME": "",
                "WAKEUP_FLOW_TEMPLATE_ID": "",
                "WAKEUP_REGEX_PATTERNS": [],
                "WAKEUP_RESPONSE": "",
                "WAKEUP_WORDS": []
              },
              "knowledgeRobotInstanceId": "",
              "llmConfig": {
                "FREQUENCY_PENALTY": 0,
                "LLM_URL": "",
                "MAX_TOKENS": 0,
                "MODEL_NAME": "",
                "NSFW_RESPONSE": "",
                "PRESENCE_PENALTY": 0,
                "PROMPT_TEMPLATE_WITHOUT_SEARCH": "",
                "RAG_TEMPLATE": "",
                "RAG_URL": "",
                "SYSTEM_PROMPT": "",
                "TEMPERATURE": 0,
                "TOP_P": 0,
                "USE_RAG": false
              },
              "llmToken": "",
              "roomType": ""
            },
            "livektUrlInfo": {
              "allRoomsUrl": "",
              "closeRoomUrl": "",
              "getRoomTokenUrl": "",
              "roomInfoUrl": "",
              "wsUrl": ""
            }
          }
          this.$nextTick(() => {
            this.$refs['form'].clearValidate();
          });
        } else {
          console.log(JSON.parse(res.data.data.projectConfig));
          this.form = {...JSON.parse(res.data.data.projectConfig)};
        }
      } catch (error) {
        console.error('获取项目配置失败:', error);
        this.$message.error('获取项目配置失败，请稍后再试');
      }
    },
    closeFn() {
      // Qrcode.clear()
    },
    downloadQR() {
      let container = document.querySelector('.qrcode')
      let img = container.querySelector('img')
      let imgSrc = img.src;
      const link = document.createElement('a');
      link.href = imgSrc;
      link.download = '二维码.jpg';
      document.body.appendChild(link);

      link.click();
      document.body.removeChild(link);
    },
    addItem(arr) {
      arr.push('')
    },
    removeItem(arr, index) {
      arr.splice(index, 1)
    },
    copyLink(val) {
      copy(val)
      this.$message.success('复制成功')
    },
    getUrl,
    creatQrCode() {
      let container = document.querySelector('.qrcode')
      container.innerHTML = ''
      this.qrcode = new Qrcode(this.$refs.qrCodeUrl, {
        text: `${this.getUrl}/aihuman/aihumanShow/index.html?id=${this.itemsData.id}`, // 需要转换为二维码的内容
        width: 100,
        height: 100,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: Qrcode.CorrectLevel.H
      })

    },
  }
}
</script>

<template>
  <huilan-dialog
    title="发布与使用"
    :visible.sync="dialogVisible"
    width="1000px"
    top="3vh"
    append-to-body
    @close="closeFn"
  >
    <div class="release-content" style="margin-bottom: 20px;">
      <div class="release-text">
        {{ getUrl() }}/aihuman/aihumanShow/index.html?id={{ itemsData.id }}

      </div>
      <div class="release-btn-block">
        <el-button type="text" @click="copyLink(`${getUrl()}/aihuman/aihumanShow/index.html?id=${itemsData.id}`)">
          复制链接
        </el-button>
      </div>
    </div>

    <div v-if="itemsData.applyType === 3" class="release-content release-content--row">
      <div class="qrcode" ref="qrCodeUrl"></div>
      <div style="margin-right: 20px;">
        扫码体验
      </div>
      <div>
        <el-button type="primary" plain size="small" style="background: #fff; color:#333;" @click="downloadQR">
          下载二维码
        </el-button>
      </div>
    </div>

    <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="top">
      <div v-for="(sectionValue, sectionName, index1) in form" :key="index1">
        <el-collapse accordion>
          <el-collapse-item>
            <template slot="title">
              {{ sectionName }}
            </template>
            <el-row :gutter="20" v-for="(value2, key2, index2) in sectionValue" :key="index2">
              <template v-if="isObject(value2)">
                <el-collapse accordion style="padding:0 15px;">
                  <el-collapse-item>
                    <template slot="title">
                      {{ key2 }}
                    </template>
                    <el-row :gutter="20">
                      <el-col :span="12" v-for="(value3, key3, index3) in value2" :key="index3">
                        <el-form-item
                          v-if="Array.isArray(form[sectionName][key2][key3])"
                          :label="key3" :prop="`${sectionName}.${key2}.${key3}`"
                        >
                          <template #label>
                            {{ key3 }}
                            <el-button type="text" @click="addItem(form[sectionName][key2][key3])">
                              添加
                            </el-button>
                          </template>
                          <el-form-item
                            v-for="(item, index) in form[sectionName][key2][key3]"
                            :key="index"
                            style="margin-bottom: 8px;"
                            :prop="`${index}.${item}`">
                            <div style="display:flex;">
                            <el-input v-model="form[sectionName][key2][key3][index]"></el-input>
                            <el-button type="text" style="margin-left: 10px;" @click="removeItem(form[sectionName][key2][key3], index)">删除</el-button>
                            </div>
                          </el-form-item>
                        </el-form-item>
                        <el-form-item v-else :label="key3" :prop="`${sectionName}.${key2}.${key3}`">
                          <el-input v-model="form[sectionName][key2][key3]"></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-collapse-item>
                </el-collapse>
              </template>
              <template v-else>
                <el-col :span="24">
                  <el-form-item :label="key2" :prop="`${sectionName}.${key2}`">
                    <el-input v-model="form[sectionName][key2]"></el-input>
                  </el-form-item>
                </el-col>
              </template>
            </el-row>
          </el-collapse-item>
        </el-collapse>
      </div>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button :loading="loading" @click="dialogVisible = false">取 消</el-button> <!-- 绑定 loading 属性 -->
      <el-button type="primary" :loading="loading" @click="submitForm('form')">确 定</el-button> <!-- 绑定 loading 属性 -->
    </span>
  </huilan-dialog>
</template>

<style scoped lang="scss">
.block-title {
  font-weight: bold;
  border-bottom: 1px solid #e4e3e3;
  margin-bottom: 20px;
  padding-bottom: 10px;
  font-size: 16px;
}

.qrcode {
  display: inline-block;
  background: #fff;
  padding: 8px;
  margin-right: 20px;

  img {
    width: 132px;
    height: 132px;
    background-color: #fff; //设置白色背景色
    padding: 10px; // 利用padding的特性，挤出白边
    box-sizing: border-box;
  }
}

.release-text {
  height: 60px;
}

.release-btn-block {
  display: flex;
  justify-content: flex-end;
  height: 20px;
  align-items: center;
}

.release-content {
  background: #EEEEEE;
  border-radius: 6px;
  color: #222222;
  padding: 15px;
  box-sizing: border-box;

  &--row {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-bottom: 20px;
  }
}
</style>
